package org.jetnuke.dao.generic;

import org.apache.log4j.Logger;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import net.jforum.JForumExecutionContext;
import net.jforum.util.preferences.SystemGlobals;

import org.jetnuke.entities.BlogHits;

public class GenericBlogHitsDAO implements org.jetnuke.dao.BlogHitsDAO {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(GenericBlogHitsDAO.class);

	public void add(BlogHits bh) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("add(BlogHits) - start"); //$NON-NLS-1$
		}

		PreparedStatement p = JForumExecutionContext.getConnection()
				.prepareStatement(SystemGlobals.getSql("BlogHitsModel.add"));
		p.setInt(1, bh.getAUTHOR_ID());
		p.setInt(2, bh.getPOST_ID());
		p.setTimestamp(3, new Timestamp(bh.getTIMESTAMP().getTime()));
		p.executeUpdate();
		p.close();

		if (logger.isDebugEnabled()) {
			logger.debug("add(BlogHits) - end"); //$NON-NLS-1$
		}
	}

	public List selectHotWeeks() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("selectHotWeeks() - start"); //$NON-NLS-1$
		}

		PreparedStatement p = JForumExecutionContext.getConnection()
				.prepareStatement(
						SystemGlobals.getSql("BlogHitsModel.selectHotWeek"));
		GregorianCalendar gc = new GregorianCalendar();
		gc.add(Calendar.WEEK_OF_YEAR, -1);
		p.setTimestamp(1, new Timestamp(gc.getTimeInMillis()));
		ResultSet rs = p.executeQuery();
		ArrayList ls = new ArrayList();
		while (rs.next()) {
			int count = rs.getInt(1);
			int author = rs.getInt(2);
			List intList = new ArrayList();
			intList.add(new Integer(count));
			intList.add(new Integer(author));
			ls.add(intList);
		}

		if (logger.isDebugEnabled()) {
			logger.debug("selectHotWeeks() - end"); //$NON-NLS-1$
		}
		return ls;
	}

}
